from django.shortcuts import render
from rest_framework.views import APIView
from .serializers import LoginSerializer
from datetime import datetime
from .authentications import generate_jwt
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import AllowAny


# Create your views here.


class LoginAPIView(APIView):
    permission_classes = [AllowAny]  # 允许任何用户访问登录接口

    def post(self, request):
        # 1. 验证数据是否可用
        serializer = LoginSerializer(data=request.data)
        if serializer.is_valid():
            # 2. 验证成功，返回结果
            user = serializer.validated_data.get('user')            # 从序列化器的attrs中获取我们封装进去的user对象
            user.last_login = datetime.now()        # 更新登录时间
            user.save()
            token = generate_jwt(user)              # 走到这里的用户是通过密码校验的，为用户生成token
            return Response({"token": token})       # 返回token
        else:
            print(serializer.errors)
            return Response({"message":"参数验证失败！"}, status=status.HTTP_400_BAD_REQUEST)


# 测试
class TestAPIView(APIView):


    def get(self, request):
        return Response({"message":"测试成功！", "code":"200"})